package com.ygou.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.SortParameters.Order;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ygou.mapper.GoodsMapper;
import com.ygou.mapper.GoodsTypeMapper;
import com.ygou.mapper.OrdersMapper;
import com.ygou.pojo.Goods;
import com.ygou.pojo.GoodsExample;
import com.ygou.pojo.GoodsExample.Criteria;
import com.ygou.pojo.GoodsType;
import com.ygou.pojo.GoodsTypeExample;
import com.ygou.pojo.GoodsWithBLOBs;
import com.ygou.pojo.Ordergoods;
import com.ygou.pojo.Orders;
import com.ygou.service.GoodService;
@Service
public class GoodServiceImpl implements GoodService{
	@Autowired
	GoodsMapper gm;
	@Autowired
	GoodsTypeMapper gtm;
	@Autowired
	SolrServer solrServer;
	@Autowired
	OrdersMapper orderMapper;
	
	public GoodsMapper getGm() {
		return gm;
	}

	public void setGm(GoodsMapper gm) {
		this.gm = gm;
	}

	@Override
	public Map<String, Object> showPage(Map<String, Object> m) {
		// TODO Auto-generated method stub
		Object curr1=m.get("currPage");
		int currPage=1;
		if(curr1!=null&&!curr1.equals("")){
			currPage=Integer.parseInt(curr1.toString());
		}
		Object nameO=m.get("selName");
		Object typeid=m.get("typeId");
		//
		GoodsExample e=new GoodsExample();
		Criteria c=e.createCriteria();
		if(nameO!=null&&nameO!=""){
			
			String name=m.get("selName").toString();
			c.andGoddstitleLike("%"+name+"%");
		}
		if(typeid!=null&&typeid!=""){
			GoodsType selType=gtm.selectByPrimaryKey(new Long(Integer.parseInt(typeid.toString())));
			if(selType.getParentid()==0){
				List<GoodsType> gts=new ArrayList<GoodsType>();
				List<Long> parentIds=new ArrayList<Long>();
				
				GoodsTypeExample gtex=new GoodsTypeExample();
				com.ygou.pojo.GoodsTypeExample.Criteria gtc=gtex.createCriteria();
				gtc.andParentidEqualTo(new Long(Integer.parseInt(typeid.toString())));
				gts=gtm.selectByExample(gtex);
				for (GoodsType gg: gts) {
					parentIds.add(gg.getId());
				}
				c.andGoodstypeidIn(parentIds);
			}else{
				
			c.andGoodstypeidEqualTo(new Long(Integer.parseInt(typeid.toString())));
			}
		}
		PageHelper.startPage(currPage, 5);
		List<Goods> ls1=gm.selectByExample(e);
		PageInfo<Goods> pages=new PageInfo<Goods>(ls1,5);
		
		m.put("pages",pages);
		return m;
	}

	@Override
	public boolean isSell(int goodid) {
		Goods g=gm.selectByPrimaryKey(goodid);
		if(g.getIssale()==1){
			Byte b=0;
			g.setIssale(b);
		}
		else{
			Byte b=1;
			g.setIssale(b);
		}
		g.setGoodsid(goodid);
		return gm.updateByPrimaryKey(g)>0;
	}

	@Override
	public GoodsWithBLOBs selById(int id) {
		return (GoodsWithBLOBs)gm.selectByPrimaryKey(id);
	}

	@Override
	public GoodsWithBLOBs selByName(String name) {
		GoodsExample e=new GoodsExample();
		Criteria c=e.createCriteria();
		c.andGoddstitleEqualTo(name);
		return (GoodsWithBLOBs) gm.selectByExampleWithBLOBs(e).get(0);
	}

	@Override
	public boolean doUpdate(GoodsWithBLOBs g) {
		return gm.updateByPrimaryKeySelective(g)>0;
	}

	@Override
	public boolean doInsert(GoodsWithBLOBs g) {
		return gm.insert(g)>0;
	}

	@Override
	public GoodsWithBLOBs selById2(int id) {
		// TODO Auto-generated method stub
		return gm.selGoodsAndTypeByGoodsId(id);
	}

	@Override
	public boolean deleteGoods(List<Integer> id) {
		// TODO Auto-generated method stub
		int count=0;
		for (Integer goodsid : id) {
			count+=gm.deleteByPrimaryKey(goodsid);
		}
		return count>0;
	}
	
	
	/********************/
	@Override
	public List<Goods> selectByExample(int goodstypeid) {
		GoodsExample example = new GoodsExample();
		Criteria c = example.createCriteria();
		//不显示下架商品
		c.andIssaleEqualTo((byte)1);
		Map<String, Object> map = new HashMap<String, Object>();
		// T恤
		c.andGoodstypeidEqualTo((long) goodstypeid);
		c.andIsbestEqualTo((byte) 1);
		return gm.selectByExample(example);
	}

	// 模糊查询
	@Override
	public List<Goods> selectByName(String name) {
		GoodsExample example = new GoodsExample();
		Criteria c = example.createCriteria();
		if (name != null && !"".equals(name)) {
			c.andGoddstitleLike("%" + name + "%");
		}
		return gm.selectByExample(example);
	}

	// 根据销量降序 显示所有信息
	@Override
	public List<GoodsType> findHotType() {
		GoodsExample example = new GoodsExample();
		example.setDistinct(true);
		example.setOrderByClause("sale desc");
		return gm.findHotType(example);
	}

	// 根据分类查询
	@Override
	public List<Goods> selectByIs(int is) {
		GoodsExample example = new GoodsExample();
		Criteria c = example.createCriteria();
		if (is == 1) {
			c.andIsbestEqualTo((byte) 1);
		} else if (is == 2) {
			c.andIshotEqualTo((byte) 1);
		} else {
			c.andIsnewEqualTo((byte) 1);
		}
		return gm.selectByExample(example);
	}

	// 根据价格区间查询商品
	@Override
	public List<Goods> selectByPrice(BigDecimal minPrice, BigDecimal maxPrice, Integer goodstypeid, String select) {
		GoodsExample example = new GoodsExample();
		Criteria c = example.createCriteria();
		if (minPrice != null && !"".equals(minPrice)) {
			c.andSalepriceGreaterThan(minPrice);
		}
		if (maxPrice != null && !"".equals(maxPrice) && maxPrice.intValue()!=0) {
			c.andSalepriceLessThan(maxPrice);
		}
		if (goodstypeid != null && !"".equals(goodstypeid)) {
			c.andGoodstypeidEqualTo(new Long(goodstypeid));
		}
		if (select != null && !"".equals(select)) {
			c.andGoddstitleLike("%"+select+"%");
		}
		return gm.selectByExample(example);
	}

	// 根据价格的降序和升序查询
	@Override
	public List<Goods> selectOrderByPrice(int flag) {
		GoodsExample example = new GoodsExample();
		if (flag == 1) {
			example.setOrderByClause("salePrice desc");
		} else {
			example.setOrderByClause("salePrice asc");
		}
		return gm.selectByExample(example);
	}
	
	
	// 根据分类查询
	@Override
	public List<Goods> selectByIs(Integer is, String seach, Integer flag, 
			BigDecimal minPrice, BigDecimal maxPrice,
			Integer goodstypeid) {
		List<Goods> list = new ArrayList<Goods>();
		Map<String, Object> map = new HashMap<String, Object>();
		if (seach != null && !"".equals(seach)) {
			map.put("seach", "%"+seach+"%");
		}
		if (flag != null && !"".equals(flag)) {
			map.put("flag",flag);
		}
		// 流行
		if (is != null && !"".equals(is)) {
			map.put("is",is);
		}
		if (minPrice != null && !"".equals(minPrice)) {
			map.put("minPrice",minPrice);
		}
		if (maxPrice != null && !"".equals(maxPrice) && maxPrice.intValue() != 0) {
			map.put("maxPrice",maxPrice);
		}
		if (goodstypeid != null && !"".equals(goodstypeid)) {
			map.put("goodstypeid",goodstypeid);
		}
		list = gm.findOrWhere(map);
		return list;
	}

	@Override
	public List<Goods> findBySolr(Map<String, Object> map) {
		String goodstitle=(String) map.get("goodstitle");
		Integer is=(java.lang.Integer) map.get("is");
		Integer flag=(Integer) map.get("flag");
		BigDecimal minPrice=(BigDecimal) map.get("minPrice");
		BigDecimal maxPrice=(BigDecimal) map.get("maxPrice");
		Integer goodstypeid=(Integer) map.get("goodstypeid");
		List<Goods> goods=new ArrayList<Goods>();
		try {
			SolrQuery query=new SolrQuery();
			//设置搜索结果高亮显示
			query.setHighlight(true);
			//设置当前页
			query.setStart(0);
			//设置每页显示条数
			query.setRows(25);
			//设置高亮前缀
			query.setHighlightSimplePre("<font color=\"red\">");
			//设置高亮后缀
			query.setHighlightSimplePost("</font>");
			query.setParam("hl.fl","item_title");
			//设置solr搜索条件
			if(goodstitle!=null && !"".equals(goodstitle)){
				query.setQuery("item_title:"+goodstitle);
			}else{
				query.setQuery("item_title:* and item_issale=1");
			}
			//按价格排序
			if (flag != null && !"".equals(flag)) {
				if(flag==1){
					query.setSort("item_price",ORDER.desc);
				}else{
					query.setSort("item_price",ORDER.asc);
				}
			}
			//根据类型
			if (goodstypeid != null && !"".equals(goodstypeid)) {
				query.setHighlightSimplePre("");
				//设置高亮后缀
				query.setHighlightSimplePost("");
				query.setFilterQueries("item_typeid:"+goodstypeid);
			}
			//流行 、热销、精品
			if (is != null && !"".equals(is)) {
				if(is==1){
					query.setSort("item_sales",ORDER.desc);
				}else if(is==2){
					query.setFilterQueries("item_hot:1");
				}else if(is==3){
					query.setFilterQueries("item_new:1");
				}
			}
			//按价格搜索 区间
			if (minPrice != null && !"".equals(minPrice)||maxPrice!=null && !"".equals(maxPrice)) {
				query.setFilterQueries("item_price:["+minPrice+" TO "+maxPrice+"]");
			}
			
			//获取返回结果
			QueryResponse result=solrServer.query(query);
			//存高亮的集合
			Map<String,Map<String, List<String>>> mapList=result.getHighlighting();
			//获取返回结果中的文档对象集合
			SolrDocumentList doucuement = result.getResults();
			//遍历文档对象集合
			for (SolrDocument solrDocument : doucuement) {
				Goods good=new Goods();
				Map<String, List<String>> fiedmap=mapList.get(solrDocument.get("id"));
				List<String> stringlist=fiedmap.get("item_title");
				for (String ms : stringlist) {
					good.setGoddstitle(ms);
				}
				good.setGoodsid(Integer.valueOf(solrDocument.get("id").toString()));
				//good.setGoddstitle((String) solrDocument.get("item_title"));
				good.setGoodsthums(solrDocument.get("item_image").toString());
				good.setSaleprice(new BigDecimal(solrDocument.get("item_price").toString()));
				good.setCollectnum(Integer.valueOf(solrDocument.get("item_cnum").toString()));
				/*good.setIshot(Byte.valueOf(solrDocument.get("item_hot").toString()));
				good.setIsnew(Byte.valueOf(solrDocument.get("item_price").toString()));*/
				goods.add(good);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return goods;
	}

	@Override
	public boolean valIsSale(Integer orderid) {
		Orders order=orderMapper.selectByPrimaryKey(orderid);
		for (Ordergoods og : order.getOgs()) {
			if(og.getGood().getIssale()==0){
				return false;
			}
		}
		return true;
	}
	
}
